$(function () {
    getCatelist();

    var index;
    var index1;
    // 2点击添加弹出弹出层
    $('#btnadd').click(function () {
        index = layer.open({
            area: ["500px", "250px"],
            title: '添加文章分类',
            content: $('#addtpl').html(),
        })
    })

    //3 添加书籍
    $('body').on('submit', '#form-add', function (e) {
        e.preventDefault();
        $.ajax({
            type: 'post',
            url: '/my/article/addcates',
            data: $(this).serialize(),
            success: function (res) {
                if (res.status !== 0) return layer.msg('添加失败')
                layer.msg('成功')
                getCatelist();
                layer.close(index);
            }
        })
    });

    //4弹出编辑框
    $('body').on('click', '.edit', function () {
        var id = $(this).attr('data-id');
        console.log(id)
        $.ajax({
            type: 'get',
            url: '/my/article/cates/' + id,
            success: function (res) {
                // console.log(res)
                layui.form.val('editform', res.data)
            }
        })
        index1 = layer.open({
            type: 1,
            area: ["500px", "250px"],
            title: '修改文章分类',
            content: $('#edittpl').html(),
        })
    })

    $('body').on('submit', '#form-edit', function (e) {
        e.preventDefault();
        $.ajax({
            type: 'post',
            url: '/my/article/updatecate',
            data: $(this).serialize(),
            success: function (res) {
                if (res.status !== 0) return layer.msg('修改失败')
                layer.msg('成功');
                getCatelist();
                layer.close(index1);
            }
        })
    });


    // 5点击删除显示弹出层
    $('body').on('click', '.remove', function () {
        var id = $(this).attr('data-id')
        layer.confirm('确定要删除?', { icon: 3, title: '提示' }, function (index) {
            //do something
            // 销毁凭证
            $.ajax({
                type: 'get',
                url: '/my/article/deletecate/' + id,
                success: function (res) {
                    if (res.status !== 0) return layer.msg('修改失败')
                    layer.msg('成功');
                    getCatelist();

                }
            })
        });
        layer.close(index)
    })
});


// 1获取文章列表数据
function getCatelist() {
    $.ajax({
        type: 'get',
        url: '/my/article/cates',
        success: function (res) {
            if (res.status != 0) return layer.msg('获取失败')
            console.log(res)

            var str = template('tpl', res);
            $(' tbody').html(str)
        }
    })
}